//
//  WriteToFileImage.m
//  MooreDoll
//
//  Created by 郭景豪 on 2014/12/9.
//  Copyright (c) 2014年 Tank. All rights reserved.
//

#import "WriteToFileImage.h"

@implementation WriteToFileImage
@synthesize savePath;

-(NSString *)savePath
{
    savePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0] stringByAppendingPathComponent:@"UserImage"];
    return savePath;
}

-(void)checkSavePath
{
    NSFileManager *fm = [NSFileManager defaultManager]; //创建NSFileManager实例

    NSLog(@"%@",self.savePath);
    
    if (![fm fileExistsAtPath:self.savePath]) {
        NSLog(@"創建相簿");

        [fm createDirectoryAtPath:self.savePath withIntermediateDirectories:YES attributes:nil error:NULL];
    }
    
}

-(NSString *)GetAndWriteToFileImage:(UIImage *)image
{
    //確認路徑
    [self checkSavePath];
    NSString *imageFilePath = [NSString stringWithFormat:@"%@/userImage.jpg",self.savePath];//取得完整路徑
    NSLog(@"%@",imageFilePath);
    NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, 0.05f)];
    //1.0f = 100% 不失真
    
    if([imageData writeToFile:imageFilePath options:NSDataWritingAtomic error:nil])//將圖片儲存
    {
        return imageFilePath;

    }else
    {
        return nil;
    }
}

-(NSString *)GetAndWriteToFileImage:(UIImage *)image fileName:(NSString *)fileName
{
    //確認路徑
    [self checkSavePath];
    
    NSString *imageFilePath = [NSString stringWithFormat:@"%@/%@.jpg",self.savePath,fileName];//取得完整路徑
    
    NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, 0.05f)];
    //1.0f = 100% 不失真
    
    if([imageData writeToFile:imageFilePath options:NSDataWritingAtomic error:nil])//將圖片儲存
    {
        return imageFilePath;
        
    }else
    {
        return nil;
    }
}

+(WriteToFileImage *)sharedInstance
{
    static WriteToFileImage *writeToFileImage;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        writeToFileImage = [[WriteToFileImage alloc] init];
    });
    
    return writeToFileImage;
}

@end
